package com.zzrt.servlet.fileupload;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

/**
 * 文件上传
 */
public class FileUploadServlet extends HttpServlet {

	private static final long serialVersionUID = 7484414007075166565L;

	@SuppressWarnings("deprecation")
	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		request.setCharacterEncoding("UTF-8");
		
		 //1、创建一个DiskFileItemFactory工厂   工厂
		 DiskFileItemFactory factory = new DiskFileItemFactory();
		 
		 //临时文件夹  当文件大小超过了setSizeThreshold设置的大小比如3M 就会保存在临时文件夹
		 String temp = request.getRealPath("/upload/user/temp");
		 
		 //正式文件夹 显示图片为例：拿的时候 从 正式文件夹中拿
		 String formal = request.getRealPath("/upload/user/formal");
		 
		 
		 System.out.println("临时文件夹所在的位置=["+temp+"]");
		 System.out.println("正式文件夹所在的位置=["+formal+"]");
		 
		 //2 设置临时文件夹
		 
		 //如果文件夹不存在就自动创建
		 if(!new File(temp).isDirectory()){
			 new File(temp).mkdirs(); 
		 }
			 
		 if(!new File(formal).isDirectory()){
			 new File(formal).mkdirs();
		 }
		 factory.setRepository(new File(temp));
		 
		 //3设置工厂的缓冲区的大小，当上传的文件大小超过缓冲区的大小时，就会生成一个临时文件存放到指定的临时目录当中
		 //单位是byte，所以这里指定的是3M
		 factory.setSizeThreshold(1024 * 1024 * 3);
		 
		 //4创建一个文件上传解析器
		 ServletFileUpload upload= new ServletFileUpload(factory);
		 
		 try {
			List<FileItem> list = upload.parseRequest(request);
			System.out.println(list.size());
			
			
			for (FileItem item : list) {
				
				if(item.isFormField()){
					
					//说明是一般的表单
					String name =item.getFieldName();
					String value= item.getString();
					request.setAttribute(name, value);
				}else{
					//说明是1个文件
					String name =item.getFieldName();
					String value= item.getName();
					int start  = value.lastIndexOf("\\");
					
					String filename = value.substring(start+1);
					
					int index = filename.lastIndexOf(".");
					System.out.println(index);
					String ext = filename.substring(index);
					System.out.println(ext);
					
					filename = UUID.randomUUID().toString()+ext;
					System.out.println(filename);
					request.setAttribute(name, filename);
					
					System.out.println("name=["+name+"],filename=["+filename+"]");
					
					//5将文件写到正式文件夹
					item.write(new File(formal,filename));
				}
			}
			
			request.getRequestDispatcher("/success.jsp").forward(request, response);
		} catch (Exception e) {
			e.printStackTrace();
		}
		 
		
	}

	
}
